package pl.edu.agh.expert.mushrooms.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

import pl.edu.agh.expert.mushrooms.Mushroom;
import pl.edu.agh.expert.mushrooms.Symptom;

public class Main {

	private static JFrame frame;
	
	private static Logger LOGGER = Logger.getAnonymousLogger();

	private static JLabel resultLabel;

	private static AnswerTableDataModel answerTableDataModel;
	
	private static JTable answerTable;

	private static JLabel questionLabel;

	private static JComboBox possibleAnswersBox;
	
	private static StatefulKnowledgeSession ksession;
	
	private static Queue<Symptom> symptomQueue = new LinkedList<Symptom>();
	
	private static Symptom symptomToPutBack;
	
	private static JButton acceptAnserButton;
	
	private static void createAndShowGUI() {
		try {
			// Set System L&F
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			LOGGER.warning("Could not set system L&F " + e);
		}

		frame = new JFrame("Mroczny grzybiarz ver. 12.6.0");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JMenuBar menuBar = new JMenuBar();
		JMenu expertizeMenu = new JMenu("Ekspertyza");
		JMenuItem newExpertizeMenuItem = new JMenuItem("Nowa");
		newExpertizeMenuItem.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				SwingUtilities.invokeLater(new Runnable() {
					
					@Override
					public void run() {
						startNewSession();
						acceptAnserButton.setEnabled(true);
					}
				});
				
			}
		});
		JMenuItem closeMenuItem = new JMenuItem("Zamknij");
		closeMenuItem.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
				
			}
		});

		expertizeMenu.add(newExpertizeMenuItem);
		expertizeMenu.add(new JSeparator());
		expertizeMenu.add(closeMenuItem);

		menuBar.add(expertizeMenu);

		frame.setJMenuBar(menuBar);

		JPanel resultsPanel = new JPanel();
		resultsPanel
				.setLayout(new BoxLayout(resultsPanel, BoxLayout.PAGE_AXIS));
		resultsPanel.add(new JLabel("Rezultat: "));
		resultsPanel.add(new JSeparator());
		resultLabel = new JLabel(" ");
		resultsPanel.add(resultLabel);
		resultsPanel.add(new JSeparator());

		answerTableDataModel = new AnswerTableDataModel();
		/*answerTableDataModel.addQuestionAnswerPair("Przykladowe pytanie",
				"Odpowiedz");*/
		answerTable = new JTable(answerTableDataModel);

		JPanel questionsPanel = new JPanel();
		questionsPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
		questionsPanel.setLayout(new BoxLayout(questionsPanel,
				BoxLayout.PAGE_AXIS));
		questionsPanel.add(new JLabel("Pytanie: "));
		questionsPanel.add(new JSeparator());

		questionLabel = new JLabel(" ");

		questionsPanel.add(questionLabel);

		String[] possibleAnswers = { " ", " " };

		possibleAnswersBox = new JComboBox(possibleAnswers);

		questionsPanel.add(possibleAnswersBox);

		acceptAnserButton = new JButton("Dalej");
		acceptAnserButton.setEnabled(false);
		acceptAnserButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				updateAnswer();
			}
		});

		questionsPanel.add(acceptAnserButton);

		frame.getContentPane().setLayout(new BorderLayout());

		frame.getContentPane().add(answerTable, BorderLayout.CENTER);
		frame.getContentPane().add(resultsPanel, BorderLayout.NORTH);
		frame.getContentPane().add(questionsPanel, BorderLayout.SOUTH);

		frame.setPreferredSize(new Dimension(400, 400));
		frame.pack();
		frame.setVisible(true);
	}

	private static void updateAnswer() {
		answerTableDataModel.addQuestionAnswerPair(symptomToPutBack.getQuestion().getQuestionText(), (String)possibleAnswersBox.getSelectedItem());
		//answerTable.setModel(answerTableDataModel);
		System.out.println(possibleAnswersBox.getSelectedIndex());
		symptomToPutBack.setStatus(possibleAnswersBox.getSelectedIndex());
		addAndFire(symptomToPutBack);
	}
	
	private static void updateView(final Symptom symptom) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				questionLabel.setText(symptom.getQuestion().getQuestionText());
				possibleAnswersBox.removeAllItems();
				for(String possibleAnswer : symptom.getQuestion().getPossibleAnswers()) {
					possibleAnswersBox.addItem(possibleAnswer);
				}
			}
		});
	}
	
	private static void addAndFire(Object object) {
		ksession.insert(object);
		ksession.fireAllRules();
	}

	private static void startNewSession() {
		try {
			// load up the knowledge base
			KnowledgeBase kbase = readKnowledgeBase();
			ksession = kbase.newStatefulKnowledgeSession();
			KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory
					.newFileLogger(ksession, "test");
			addAndFire(new Mushroom());
			logger.close();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private static KnowledgeBase readKnowledgeBase() throws Exception {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();
		kbuilder.add(ResourceFactory.newClassPathResource("Mushrooms.drl"),
				ResourceType.DRL);
		kbuilder.add(ResourceFactory.newClassPathResource("Mushrooms_Questions.drl"),
				ResourceType.DRL);
		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		if (errors.size() > 0) {
			for (KnowledgeBuilderError error : errors) {
				System.err.println(error);
			}
			throw new IllegalArgumentException("Could not parse knowledge.");
		}
		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		return kbase;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});

	}

	public static void addSymptomToAsk(Symptom symptom) {
		//symptomQueue.add(symptom);
		symptomToPutBack = symptom;
		updateView(symptom);
	}
	
	public static void setResult(final Mushroom mushroom) {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				resultLabel.setText(mushroom.getResult());
				acceptAnserButton.setEnabled(false);
				ImageIcon icon = new ImageIcon("src/main/resources/"+mushroom.getResult()+".jpg","grzyb");
				JOptionPane.showMessageDialog(frame, mushroom.getResult(), "Wynik", JOptionPane.INFORMATION_MESSAGE,
					    icon);
			}
		});
	}
	
	public static int askQuestion(final String question, final String[] answers) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				answerTableDataModel.addQuestionAnswerPair(questionLabel.getText(), (String)possibleAnswersBox.getSelectedItem());
				questionLabel.setText(question);
				possibleAnswersBox = new JComboBox(answers);
			}
		});
		return -1;
	}

}
